'use strict';

// 云对象名：interaction-service
module.exports = {
  /**
   * 切换收藏状态
   * @param {object} params - 参数对象
   * @param {string} params.contentId - 资源ID
   * @param {string} params.contentType - 资源类型（exam/rule/video/notice）
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @returns {object} 切换结果
   */
  async toggleFavorite({ contentId, contentType, userId, token } = {}) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      if (!contentId || !contentType) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 检查是否已收藏
      const existingFavorite = await db.collection('user_favorites')
        .where({
          user_id: currentUserId,
          resource_id: contentId,
          resource_type: contentType
        })
        .get();
      
      let isFavorited = false;
      
      if (existingFavorite.data && existingFavorite.data.length > 0) {
        // 已收藏，取消收藏
        await db.collection('user_favorites').doc(existingFavorite.data[0]._id).remove();
        isFavorited = false;
      } else {
        // 未收藏，添加收藏
        await db.collection('user_favorites').add({
          user_id: currentUserId,
          resource_id: contentId,
          resource_type: contentType,
          create_date: new Date()
        });
        isFavorited = true;
      }
      
      return {
        code: 0,
        message: isFavorited ? '收藏成功' : '取消收藏成功',
        data: {
          isFavorited: isFavorited
        }
      };
    } catch (error) {
      console.error('切换收藏状态失败:', error);
      return {
        code: -1,
        message: '操作失败: ' + error.message
      };
    }
  },

  /**
   * 检查收藏状态
   * @param {string} resourceId - 资源ID
   * @param {string} resourceType - 资源类型
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 收藏状态
   */
  async checkFavorite(resourceId, resourceType, userId, token) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      if (!resourceId || !resourceType) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 检查是否已收藏
      const favoriteResult = await db.collection('user_favorites')
        .where({
          user_id: currentUserId,
          resource_id: resourceId,
          resource_type: resourceType
        })
        .get();
      
      const isFavorited = favoriteResult.data && favoriteResult.data.length > 0;
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          isFavorited: isFavorited
        }
      };
    } catch (error) {
      console.error('检查收藏状态失败:', error);
      return {
        code: -1,
        message: '检查失败: ' + error.message
      };
    }
  },

  /**
   * 获取用户收藏列表
   * @param {object} params - 参数对象
   * @param {string} params.userId - 用户ID
   * @param {string} params.token - 用户token
   * @param {string} params.type - 资源类型（可选）
   * @param {number} params.page - 页码
   * @param {number} params.pageSize - 每页数量
   * @returns {object} 收藏列表
   */
  async getFavoriteList({ userId, token, type, page = 1, pageSize = 10 } = {}) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = { user_id: currentUserId };
      if (type) {
        where.resource_type = type;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * pageSize;
      
      // 查询收藏列表
      const favoritesResult = await db.collection('user_favorites')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(pageSize)
        .get();
      
      // 查询总数
      const countResult = await db.collection('user_favorites')
        .where(where)
        .count();
      
      // 获取收藏的资源详情
      const favorites = favoritesResult.data || [];
      const enrichedFavorites = [];
      
      for (const favorite of favorites) {
        let resourceDetail = null;
        
        try {
          switch (favorite.resource_type) {
            case 'exam':
              const examResult = await db.collection('exam_papers').doc(favorite.resource_id).get();
              resourceDetail = examResult.data;
              break;
            case 'rule':
              const ruleResult = await db.collection('rule_contents').doc(favorite.resource_id).get();
              resourceDetail = ruleResult.data;
              break;
            case 'video':
              const videoResult = await db.collection('learning_videos').doc(favorite.resource_id).get();
              resourceDetail = videoResult.data;
              break;
            case 'notice':
              const noticeResult = await db.collection('notices').doc(favorite.resource_id).get();
              resourceDetail = noticeResult.data;
              break;
          }
        } catch (error) {
          console.error('获取资源详情失败:', error);
        }
        
        // 构建前端期望的数据格式
        const favoriteItem = {
          _id: favorite._id,
          content_id: favorite.resource_id,
          content_type: favorite.resource_type,
          title: resourceDetail?.title || '未知内容',
          summary: resourceDetail?.summary || resourceDetail?.description || '',
          create_date: favorite.create_date ? new Date(favorite.create_date).getTime() : null,
          resource_detail: resourceDetail
        };
        
        enrichedFavorites.push(favoriteItem);
      }
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: enrichedFavorites,
        total: countResult.total,
        page: page,
          pageSize: pageSize
        }
      };
    } catch (error) {
      console.error('获取用户收藏列表失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 增加活动浏览量
   * @param {string} activityId - 活动ID
   * @returns {object} 增加结果
   */
  async increaseActivityViewCount(activityId) {
    try {
      const db = uniCloud.database();
      
      if (!activityId) {
        return {
          code: -1,
          message: '活动ID不能为空'
        };
      }
      
      // 增加浏览量
      await db.collection('activities').doc(activityId).update({
        view_count: db.command.inc(1),
        last_view_time: new Date()
      });
      
      return {
        code: 0,
        message: '浏览量增加成功'
      };
    } catch (error) {
      console.error('增加活动浏览量失败:', error);
      return {
        code: -1,
        message: '操作失败: ' + error.message
      };
    }
  },

  /**
   * 增加通知浏览量
   * @param {string} noticeId - 通知ID
   * @returns {object} 增加结果
   */
  async increaseNoticeViewCount(noticeId) {
    try {
      const db = uniCloud.database();
      
      if (!noticeId) {
        return {
          code: -1,
          message: '通知ID不能为空'
        };
      }
      
      // 增加浏览量
      await db.collection('notices').doc(noticeId).update({
        view_count: db.command.inc(1),
        last_view_time: new Date()
      });
      
      return {
        code: 0,
        message: '浏览量增加成功'
      };
    } catch (error) {
      console.error('增加通知浏览量失败:', error);
      return {
        code: -1,
        message: '操作失败: ' + error.message
      };
    }
  }
}; 